const socketWrapper = require('./index');
const { redisGet } = require('../utils/redis')
const { setRead } = require('../model/msg')

// 等待 Socket.IO 初始化完成后再使用
function setMsgRead() {
    try {
        const io = socketWrapper.getIO();
        io.on('connection', async (socket) => {
            socket.on('setRead', async (data, callback) => {
                if (!data.to) {
                    callback({
                        code: 500,
                        message: 'to not found'
                    });
                    return;
                }
                if (!data.msgKeys) {
                    callback({
                        code: 500,
                        message: 'msgKeys not found'
                    });
                    return;
                }
                if (!Array.isArray(data.msgKeys)) {
                    callback({
                        code: 500,
                        message: 'msgKeys数据格式不正确'
                    });
                }
                await setRead(data.msgKeys);
                callback({
                    code: 200,
                    message: 'success'
                });
                // 通知发送人
                const fromUserInfo = await redisGet(`mim-${socket.imKey}`)
                const toUserInfo = await redisGet(`mim-${data.to}`)
                let fromImKey = ''
                if (fromUserInfo && fromUserInfo.userType === 3) {
                    const serviceInfo = await redisGet('mim-IMservice')
                    if (serviceInfo) fromImKey = serviceInfo.imKey
                }
                if (toUserInfo && toUserInfo.online === 1) {
                    socket.to(toUserInfo.socketId).emit('setRead', {
                        from: fromImKey ? fromImKey : socket.imKey,
                        msgKeys: data.msgKeys
                    });
                } else {
                    callback({
                        code: 500,
                        message: '不在线'
                    });
                }
            });
        });
    } catch (error) {
        console.error('Socket.IO 未初始化:', error);
        callback({
            code: 500,
            message: error.message
        });
    }
}

module.exports = setMsgRead;
